package main

import (
	"encoding/base32"
	"github.com/sausheong/gwp/Chapter_2_Go_ChitChat/chitchat/data"
	"net/http"
)

func login(writer http.ResponseWriter, reqeust *http.Request) {
	t := parseTemplateFiles("login.layout", "public,navbar", "login")
	t.Execute(writer, nil)
}

func signup(writer http.ResponseWriter, request *http.Request)  {
	generateHTML(writer, nil, "login.layout", "public navbar", "signup")
}

func signupAccount(writer http.ResponseWriter, request *http.Request)  {
	err := request.ParseForm()
	if err != nil {
		danger(err, "can not parse form")
	}
	user := data.User{
		Name:	request.PostFormValue("name"),
		Email:	request.PostFormValue("email"),
		password:	request.PostFormValue("password"),
	}
	if err := user.Create(); err != nil {
		danger(err, "can not create user")
	}
	http.Redirect(writer, request, "/login", 302)
}

func authenticate(writer http.ResponseWriter, request http.Request)  {
	err := request.ParseForm()
	user, err := data.UserByEmail(request.PostFormValue("email"))
	if err != nil {
		danger(err, "cannot find user")
	}
	if user.Password == data.Encrypt(request.PostFormValue("password")) {
		session, err := user.CreateSession()


		if err != nil {
			danger(err, "cannot create session")
		}
		cookie := http.Cookie{
			Name:	"_cookie",
			Value: session.Uuid,
			HttpOnly: true,
		}
		http.SetCookie(writer, &cookie)
		http.Redirect(writer, request, "/", 302)
	} else {
		http.Redirect(writer, request, "/login", 302)
	}
}

func logout(writer http.ResponseWriter, request *http.Request) {
	cookie, err := request.Cookie("_cookie")
	if err != http.ErrNoCookie {
		warning(err, "huoqu cookie shibai")
		session := data.Session{Uuid: cookie.Value}
		session.DeleteBuUUID()
	}
	http.Redirect(writer, request, "/login", 302)
}


